﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Xml.Linq;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text.RegularExpressions;

namespace ulc
{
    [CollectionDataContract(Namespace = "")]
    public class StringList : List<string>
    {
        public StringList() { }

        public StringList(IEnumerable<string> items) : base(items) { }
    }

    [DataContract(Namespace = "")]
    public class LocalData
    {
        public LocalData() {
            MeetingNumbers = new StringList();
        }
        [DataMember(Order = 1)]
        public string LoginEmail { get; set; }

        [DataMember]
        public string LoginPass { get; set; }

        [DataMember]
        public bool LoginMemberMe { get; set; }

        [DataMember]
        public StringList MeetingNumbers { get; set; }

        [DataMember]
        public string MeetingName { get; set; }



        public static void SaveToJSON<T>(T data, string filePath)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                serializer.WriteObject(stream, data);
                string json = Encoding.UTF8.GetString(stream.ToArray());
                File.WriteAllText(filePath, json);
            }
        }
        public static T LoadFromJSON<T>(string filePath)
        {
            try
            {
                string text = File.ReadAllText(filePath);
                text = Regex.Replace(text, "\\{[\\n\\r ]*\"__type", "{\"__type");
                using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(text)))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                    T data = (T)serializer.ReadObject(stream);
                    return data;
                }
            }
            catch (System.Exception ex)
            {
                //logger.Error("Cannot deserialize json " + filePath, ex);
                throw;
            }
        }
    }
}
